﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace olierFrm.Extensions.EDataTable
{
    public static class EDataTable
    {
        /// <summary>
        /// 获取DataTable的唯一字段名称
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GetDataRowIndexFieldName(this DataTable dt)
        {
            if (dt == null) return null;
            return dt.TableName + "_DataRowIndex";
        }

        /// <summary>
        /// 过滤DataTable
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static System.Data.DataTable SelectToDataTable(this DataTable dt, string filter)
        {
            var dtNew = dt.Clone();
            var dtRows = dt.Select(filter);
            foreach (var r in dtRows)
            {
                dtNew.Rows.Add(r.ItemArray);
            }
            return dtNew;
        }

        /// <summary>
        /// 增加唯一字段
        /// </summary>
        /// <param name="dt"></param>
        public static void AddDataRowIndex(this DataTable dt)
        {
            string columnName = dt.GetDataRowIndexFieldName();
            dt.Columns.Add(columnName, Type.GetType("System.Int32"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i][columnName] = i;
            }
        }



        public static void AddHideColumn(this DataTable dtSource, List<string> hiddenField)
        {
            hiddenField.Remove("");
            if (hiddenField.Count == 0) return;

            if (dtSource.ExtendedProperties.ContainsKey("HideColumn"))
            {
                var dtSourceHiddenField = (List<string>)dtSource.ExtendedProperties["HideColumn"];
                foreach (var f in dtSourceHiddenField)
                {
                    if (!hiddenField.Contains(f))
                        dtSourceHiddenField.Add(f);
                }
                dtSourceHiddenField.Remove("");
            }
            else
            {
                hiddenField.Remove("");
                //hiddenField.Add("Color");
                dtSource.ExtendedProperties.Add("HideColumn", hiddenField);
            }
        }
        public static List<string> GetHideColumn(this DataTable dtSource)
        {
            if (dtSource.ExtendedProperties.ContainsKey("HideColumn"))
                return (List<string>)dtSource.ExtendedProperties["HideColumn"];
            return new List<string>();
            //foreach (var h in columnsName)
            //{
            //    if (dt.Columns.Contains(h))
            //        dt.Columns.Remove(h);
            //}
        }

    }
}
